//
//  AliOSSObject.swift
//  Swift-Codedase
//
//  Created by xyanl on 2023/7/23.
//
//  上传的文件信息
import UIKit
import SwiftUI

enum OSSObjectType {
    /// 图片
    case image
    /// 视频
    case video
    /// 文件
    case file
}


class AliOSSObject: NSObject {
    
    // MARK: 上传文件
    // uploadingData 和 uploadingFileURL 二选一
    /// 要上传的内存数据。
    var uploadingData: Data?
    /// 要上传的本地文件路径。
    var uploadingFileURL: URL?
    
    /// 文件名称(包含扩展名) 自己重新命名的时候使用，没有设置，则以当前时间戳作为文件名称。
    var name: String = ""
    /// 原文件名(包含扩展名)
    var originalName: String = ""
    /// 扩展名
    var extensionName: String = ""
    /// 上传成功后的网络地址
    var url: String = ""
    /// 文件类型
    var type: OSSObjectType = .image
    
    
    // MARK: 只有文件是视频的时候，派生出的封面信息。
    
    /// 是否需要上传视频封面
    var isUploadCover: Bool = false
    /// 封面的二进制数据
    var coverData: Data?
    /// 封面的名字
    var coverName: String?
    /// 封面的网络地址
    var coverUrl: String?
    
    override init() {
        super.init()
    }
    
    init(_ image: UIImage) {
        super.init()
        type = .image
        extensionName = "png"
        uploadingData = image.pngData()
        // 文件名: 宽x高_文件名iOSindex
        name = "\(Int(image.size.width))" + "x" + "\(Int(image.size.height))" + "_" + "\(fileNameFromMD5TimestampArc4random())" + "iOS" + "." + extensionName
    }
    
    
    init(uploadingFileURL: URL, type: OSSObjectType = .image, isUploadCover: Bool = false, index: Int = 0) {
        self.uploadingFileURL = uploadingFileURL
        self.type = type
        self.isUploadCover = isUploadCover
        super.init()
        
        switch type {
        case .image:
            
            guard let image = UIImage(contentsOfFile: uploadingFileURL.path) else {
                xLog("获取图片失败")
                return
            }
            
            originalName = uploadingFileURL.lastPathComponent
            
            if originalName.lowercased().hasSuffix(".png") {
                // 含有扩展名
                extensionName = "png"
                uploadingData = image.pngData()
                
            } else if originalName.lowercased().hasSuffix(".heic") {
                extensionName = "heic"
                if #available(iOS 17.0, *) {
                    uploadingData = image.heicData()
                } else {
                    uploadingData = image.jpegData(compressionQuality: 1)
                }
                
            } else {
                // 没有扩展名
                extensionName = "jpeg"
                uploadingData = image.jpegData(compressionQuality: 1)
            }
            
            // 文件名: 宽x高_文件名iOSindex
            name = "\(Int(image.size.width))" + "x" + "\(Int(image.size.height))" + "_" + "\(fileNameFromMD5TimestampArc4random())" + "iOS" + "\(index)" + "." + extensionName
            
        case .video:
            
            if let data = try? Data.init(contentsOf: uploadingFileURL) {
                uploadingData = data
            }
            
            let videoName = "\(fileNameFromMD5TimestampArc4random())" + "iOS" + "\(index)"
            
            originalName = uploadingFileURL.lastPathComponent
            
            if originalName.contains(".") {
                // 含有扩展名
                extensionName = originalName.components(separatedBy: ".").last!
                // 视频名
                name = "\(videoName).\(extensionName)"
                
            } else {
                // 没有扩展名
                extensionName = ""
                // 视频名
                name = videoName
            }
            
            if isUploadCover {
                // 封面 图片
                
                guard let image = UIImage.imageFromVideo(uploadingFileURL.absoluteString) else {
                    xLog("封面获取失败")
                    return
                }
                
                coverName = "\(Int(image.size.width))" + "x" + "\(Int(image.size.height))" + "_" + "\(fileNameFromMD5TimestampArc4random())" + "iOS" + "\(index)" + ".png"
                coverData = image.pngData()
            }
            
        case .file:
            
            // 文件不使用 url 上传, 可能没有权限访问
            self.uploadingFileURL = nil
            uploadingData = try! Data(contentsOf: uploadingFileURL, options: .mappedIfSafe)
            
            originalName = uploadingFileURL.lastPathComponent
            
            if originalName.contains(".") {
                // 含有扩展名
                extensionName = originalName.components(separatedBy: ".").last!
                name = "\(fileNameFromMD5TimestampArc4random())" + "iOS" + "\(index)" + ".\(extensionName)"
                
            } else {
                // 没有扩展名
                name = "\(fileNameFromMD5TimestampArc4random())" + "iOS" + "\(index)"
            }
            
            
        }
    }
    
    /// 创建文件名, 当前16位时间戳的md5加密+随机数
    func fileNameFromMD5TimestampArc4random() -> String {
        let timestamp = Date.sg.timestamp()
        return "\(String(timestamp).sg.md5Encrypt(.lowercase16))\(arc4random()%10000)"
    }
}
